import cache from "@/utils/cache";
import axios from 'axios';
import qs from 'qs'
import { Toast } from "mint-ui";
import router from '../router';
import { MessageBox } from "mint-ui";
// 创建axios实例
export const instance = axios.create({
    domain:'http://m.zhugongzhe.com',
  //baseURL: 'http://api.zhugongzhe.com',
  baseURL: 'http://localhost:27260/',  // api的base_url process.env.BASE_API or 'http://192.168.0.139'
   timeout: 5 * 1000                   // 请求超时时间
})
// 初始化默认post header
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// request拦截器
instance.interceptors.request.use(config => {
   const configHeaders = { 
       'Authorization':`Bearer ${cache.getLocal('zgz_token')}`,
   }
   Object.assign(config.headers, configHeaders);
   return config
}, error => {
   // Do something with request error
   console.log(error) // for debug
   Promise.reject(error)
})
// respone拦截器
instance.interceptors.response.use(response => {
   const res = response.data.StatusCode;
   if (res==400||res==403||res==405) {
   // Toast("token已失效，正在重新登录");
    setTimeout(()=>{
        router.push('/auth/login');
    },2000);
   }
  return response;
}, error => {
    MessageBox({
       message: error.message, // '服务器繁忙，请稍后重试'
       type: 'error',
       duration: 5 * 1000
   })
   return Promise.reject(error)
})

export const request_t= async(url = '', type = 'GET', data = {}) => {
   let result
   type = type.toUpperCase()

   if (type === 'GET') {
       await instance.get(url, { params: data })
       .then(res => {
           result = res.data
       })
   } else if (type === 'POST') {
       await instance.post(url, qs.stringify(data))
       .then(res => {
           result = res.data
       })
   }
   return result
}

